package com.zenithmind.coding.config.security;

import com.zenithmind.common.config.AuthInterceptorConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 认证拦截器配置策略 - 遵循策略模式，专门处理认证拦截器的配置
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Component
public class AuthInterceptorConfigurationStrategy implements BeanPostProcessor {

    private final SecurityEndpointRegistry endpointRegistry;

    public AuthInterceptorConfigurationStrategy(SecurityEndpointRegistry endpointRegistry) {
        this.endpointRegistry = endpointRegistry;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof AuthInterceptorConfig.AuthProperties && "authProperties".equals(beanName)) {
            configureAuthInterceptor((AuthInterceptorConfig.AuthProperties) bean);
        }
        return bean;
    }

    /**
     * 配置认证拦截器
     * 
     * @param properties 认证属性
     */
    private void configureAuthInterceptor(AuthInterceptorConfig.AuthProperties properties) {
        try {
            String[] publicEndpoints = endpointRegistry.getAllPublicEndpoints();
            properties.setSkipPaths(Arrays.asList(publicEndpoints));
            
            log.info("已为在线编程服务认证拦截器设置统一的跳过路径配置");
            log.debug("跳过路径数量: {}", publicEndpoints.length);
            
            if (log.isTraceEnabled()) {
                log.trace("跳过路径详情: {}", Arrays.toString(publicEndpoints));
            }
            
        } catch (Exception e) {
            log.error("配置认证拦截器失败", e);
            throw new RuntimeException("认证拦截器配置失败", e);
        }
    }

    /**
     * 获取配置策略名称
     * 
     * @return 策略名称
     */
    public String getStrategyName() {
        return "AuthInterceptorConfiguration";
    }

    /**
     * 验证配置是否有效
     * 
     * @return 是否有效
     */
    public boolean validateConfiguration() {
        try {
            String[] publicEndpoints = endpointRegistry.getAllPublicEndpoints();
            boolean isValid = publicEndpoints.length > 0;
            
            if (!isValid) {
                log.warn("认证拦截器配置验证失败：没有配置公开端点");
            }
            
            return isValid;
        } catch (Exception e) {
            log.error("认证拦截器配置验证异常", e);
            return false;
        }
    }

    /**
     * 重新配置认证拦截器（支持动态更新）
     * 
     * @param properties 认证属性
     */
    public void reconfigure(AuthInterceptorConfig.AuthProperties properties) {
        log.info("重新配置认证拦截器");
        configureAuthInterceptor(properties);
    }
}
